package com.molyfun.parents.activity.organization;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.organization.adapter.SigUpEnteringListAdapter;
import com.molyfun.parents.fragment.dialog.OrganizationOptionDialogFragment;
import com.molyfun.parents.fragment.dialog.OrigiationEnterFragment;
import com.molyfun.parents.push.PushMsgCacheCenter;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.OrganizationListResponse;
import com.molyfun.parents.rest.bean.UserResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.LoginTIMUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.TwoTabBar;
import com.molyfun.parents.view.swipeRefreshLayout.SwipeRefreshLayout;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:04/05/17.
 */
public class OrganizationActivity extends BaseActivity implements View.OnClickListener, TwoTabBar.TwoBarClickListener,
        SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener, SigUpEnteringListAdapter.SigUpEnteringListCallBack ,OrganizationListAdapter.OrganizationListCallBack{

    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @InjectView(R.id.organization_list)
    RecyclerView mRecyclerView;
    @InjectView(R.id.empty_layout)
    LinearLayout mEmptyLayout;
    @InjectView(R.id.organization_enter)
    TextView mEnterOrganization;
    @InjectView(R.id.base_title_left)
    ImageView mBackBtn;
    @InjectView(R.id.submit)
    TextView mSubmit;
    @InjectView(R.id.base_title)
    TextView mTitle;

    boolean showInviteOption = true;

    private LinearLayoutManager mLayoutManager;
    private OrganizationListAdapter mOrganizationListAdapter;
//    private SigUpEnteringListAdapter mSigUpEnteringListAdapter;
//    private String mCodeValue = "";

    public static final void startForResultActivity(Activity context, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(context, OrganizationActivity.class);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setClass(context, OrganizationActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_organization);
        ButterKnife.inject(this);
        getSupportActionBar().setTitle("");

        mBackBtn.setOnClickListener(this);
        mSubmit.setOnClickListener(this);
        mEnterOrganization.setOnClickListener(this);

        mTitle.setText("切换机构");
        mSubmit.setText("确定");
//
//        mTwoTabBar.initData("已入学", "已报名");
//        mTwoTabBar.setTwoBarClickListener(this);
//        mTwoTabBar.setVisibility(View.GONE);


        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
//        if (mTwoTabBar.getCurrentChooseTab() == TwoTabBar.TwoTabChooseTab.BAR_ONE) {
            mOrganizationListAdapter = new OrganizationListAdapter(this);
            mRecyclerView.setAdapter(mOrganizationListAdapter);
            mOrganizationListAdapter.setOrganizationListListener(this);
//        } else {
//            mSigUpEnteringListAdapter = new SigUpEnteringListAdapter(this);
//            mRecyclerView.setAdapter(mSigUpEnteringListAdapter);
//            mSigUpEnteringListAdapter.setSigUpEnteringListListener(this);
//        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrganizationList(true);
    }

    @Override
    public void onTwoBarClick(int chooseTab) {
        switch (chooseTab) {
            case TwoTabBar.TwoTabChooseTab.BAR_ONE:
                mOrganizationListAdapter = new OrganizationListAdapter(this);
                mRecyclerView.setAdapter(mOrganizationListAdapter);
                getOrganizationList(true);
                mSubmit.setVisibility(View.VISIBLE);
                break;
//            case TwoTabBar.TwoTabChooseTab.BAR_TWO:
//                mSigUpEnteringListAdapter = new SigUpEnteringListAdapter(this);
//                mRecyclerView.setAdapter(mSigUpEnteringListAdapter);
//                getOrganizationList(true);
//                mSubmit.setVisibility(View.GONE);
//                break;
        }
    }

//    private OrganizationListResponse.Organization organizationCache;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
               finish();
                break;
            case R.id.submit:
                if (mOrganizationListAdapter.getChoosedOrganization() != null) {
//                    organizationCache = mOrganizationListAdapter.getChoosedOrganization();
                    changeOrganization(mOrganizationListAdapter.getChoosedOrganization().getId(), mOrganizationListAdapter.getChoosedOrganization().getStudentid());
                }

                break;
            case R.id.organization_enter:
                new OrganizationOptionDialogFragment.OrganizationOptionDialogBuilder(showInviteOption)
                        .setOrganizationCallback(new OrganizationOptionDialogFragment.OrganizationOptionCallback() {
                            @Override
                            public void onOrganizationInvite() {
                                new OrigiationEnterFragment.OrigiationEnterDialogBuilder(true)
                                        .build(getSupportFragmentManager().beginTransaction());
                            }

                            @Override
                            public void onOrganizationApply() {
                                //孩子基本信息
//                                new OrigiationApplyFragment.OrigiationApplyDialogBuilder()
//                                        .build(getSupportFragmentManager());
                                //进行二维码扫描
//                                SignUpStartActivity.startActivity(OrganizationActivity.this);
//                                OrganizationEnterActivity.startActivity(OrganizationActivity.this);
//                                loadData(mCodeValue);
                                OrganizationEnterActivity.startActivity(OrganizationActivity.this);
                            }
                        })
                        .build(getSupportFragmentManager().beginTransaction());
                break;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        toast("返回");
    }

    @Override
    public void onRefresh() {
        getOrganizationList(true);
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
    }

    @Override
    public void onLoad() {
        if (mHasMoreData) {
//            if (mTwoTabBar.getCurrentChooseTab() == TwoTabBar.TwoTabChooseTab.BAR_ONE) {
                mCurrentPage++;
//            } else {
//                if (page == mCurrentPage) {
//                    mCurrentPage = page;
//                }
//            }
            mSwipeRefreshLayout.setRefreshing(false);
            mSwipeRefreshLayout.setLoading(false);
            getOrganizationList(false);
        } else {
            mSwipeRefreshLayout.setRefreshing(false);
            mSwipeRefreshLayout.setLoading(false);
        }
    }

    private int mCurrentPage = RestClient.DEFAULT_PAGE;
    private boolean mHasMoreData = true;
    private int page;

    private void getOrganizationList(final boolean isRefresh) {
        if (isRefresh) {
            mCurrentPage = RestClient.DEFAULT_PAGE;
        }
        showProgressDialog();
//        if (mTwoTabBar.getCurrentChooseTab() == TwoTabBar.TwoTabChooseTab.BAR_ONE) {
            Call<OrganizationListResponse> call = MFPApplication.getInstance().getRestClient().getOrganizationList("pass", RestClient.DEFAULT_PAGE, RestClient.LARGE_PAGE_SIZE);
            call.enqueue(new Callback<OrganizationListResponse>() {
                @Override
                public void onResponse(Call<OrganizationListResponse> call, Response<OrganizationListResponse> response) {
                    dismissProgressDialog();
                    updateCurrentStuStatus(response.body().getData());
                    if (response.body() != null && response.body().getData() != null && response.body().getData() != null) {
                        if (response.body().getData().size() > 0) {
//                            if(mTwoTabBar.getCurrentChooseTab() == TwoTabBar.TwoTabChooseTab.BAR_ONE){
//                                showInviteOption = false;
//                            }
                            mOrganizationListAdapter.refreshData(response.body().getData(),TwoTabBar.TwoTabChooseTab.BAR_ONE);
                            mEmptyLayout.setVisibility(View.GONE);
                            mSubmit.setVisibility(View.VISIBLE);
                        } else {
                            mOrganizationListAdapter.clearAll();
                            mEmptyLayout.setVisibility(View.VISIBLE);
                            mSubmit.setVisibility(View.GONE);
                        }
                    } else {
                        mOrganizationListAdapter.clearAll();
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        mSubmit.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFailure(Call<OrganizationListResponse> call, Throwable t) {
                    mOrganizationListAdapter.clearAll();
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    dismissProgressDialog();
                }
            });
//        } else {
//            Call<SignUpListResponse> signUpListResponseCall = MFPApplication.getInstance().getRestClient().signUpList(String.valueOf(mCurrentPage), String.valueOf(RestClient.LARGE_PAGE_SIZE));
//            signUpListResponseCall.enqueue(new Callback<SignUpListResponse>() {
//                private List<SignUpListResponse.DataBean.RecordsBean> records;
//
//                @Override
//                public void onResponse(Call<SignUpListResponse> call, Response<SignUpListResponse> response) {
//                    dismissProgressDialog();
//                    if (response.body() != null && response.body().getData() != null) {
//                        if (response.body().getData().getRecords().size() > 0) {
//                            records = response.body().getData().getRecords();
//                            page = response.body().getData().getPages();
//                            mSigUpEnteringListAdapter.refreshData(records, mTwoTabBar.getCurrentChooseTab());
//                            mEmptyLayout.setVisibility(View.GONE);
//                        } else {
//                            mSigUpEnteringListAdapter.clearAll();
//                            mOrganizationListAdapter.clearAll();
//                            mEmptyLayout.setVisibility(View.VISIBLE);
//                        }
//                    } else {
//                        mSigUpEnteringListAdapter.clearAll();
//                        mOrganizationListAdapter.clearAll();
//                        mEmptyLayout.setVisibility(View.VISIBLE);
//                    }
//                }
//
//                @Override
//                public void onFailure(Call<SignUpListResponse> call, Throwable t) {
//                    mOrganizationListAdapter.clearAll();
//                    mSigUpEnteringListAdapter.clearAll();
//                    mEmptyLayout.setVisibility(View.VISIBLE);
//                    dismissProgressDialog();
//                }
//            });
//        }

    }

    /*更新当前学生的入学状态*/
    private void updateCurrentStuStatus(List<OrganizationListResponse.Organization> list){
        try {
            if (list == null || list.size() == 0){
                MFPApplication.getInstance().getUser().getDepartlist().clear();
                return;
            }
            String selectedStuId = "";
            for (OrganizationListResponse.Organization organization : list) {
                if (organization.isSelected()){
                    selectedStuId = organization.getStudentid();
                    List<UserResponse.DepartBean> departs = MFPApplication.getInstance().getUser().getDepartlist();
                    if (departs == null || departs.size() == 0){
                        return;
                    }
                    for (UserResponse.DepartBean departBean : departs) {
                        if (selectedStuId.equals(departBean.getStudentid())){
                            departBean.setStatus(organization.getStatus());
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void changeOrganization(String departId, String studentId) {
        showProgressDialog();

        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().changeOrganization(departId, studentId);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getCode() == 200) {
//                    toast("切换机构成功");
                    LoginTIMUtil.getInstance().logout();
                    getUserInfo();
                } else {
//                    dismissProgressDialog();
                    toast("切换失败");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                toast("切换失败");
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void refreshSigUpEnteringListData() {
        getOrganizationList(true);
    }

    @Override
    public void refreshOrganizationListData() {
            getOrganizationList(true);
    }


    private void getUserInfo(){
        Call<UserResponse> call = MFPApplication.getInstance().getRestClient().getUserInfo();
        call.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                if (response.body() != null && response.body().getCode() == 200 && response.body().getData() != null ) {
                    MFPApplication.getInstance().setUser(response.body().getData());
                    PreferencesStorageUtil.setUserBean(OrganizationActivity.this, GsonUtil.toJson(response.body().getData()));
                    PreferencesStorageUtil.setIMUserName(OrganizationActivity.this, response.body().getData().getImusername());
                    PreferencesStorageUtil.setIMUserPwd(OrganizationActivity.this, response.body().getData().getImpassword());
                    PreferencesStorageUtil.setStudentId(OrganizationActivity.this, response.body().getData().getStudentid());
                    PreferencesStorageUtil.setPhoneNum(OrganizationActivity.this, response.body().getData().getPhone());
                    PreferencesStorageUtil.setAddress(OrganizationActivity.this, response.body().getData().getAddress());
                    PreferencesStorageUtil.setEmail(OrganizationActivity.this, response.body().getData().getEmail());
                    if(TextUtils.isEmpty(response.body().getData().getStudentid())){
                        PreferencesStorageUtil.setUserEnter(OrganizationActivity.this, false);
                    }else{
                        PreferencesStorageUtil.setUserEnter(OrganizationActivity.this, true);
                        PreferencesStorageUtil.setOriganOutShowSplash(MFPApplication.getInstance(), false);
                    }
                    PushMsgCacheCenter.getInstance().setmCurrentUnreadCount(response.body().getData().getMessageunreadcount());

                    Message uimessage = new Message();
                    uimessage.what = EventDispatcherEnum.UI_EVENT_CHANGE_USERINFO;
                    MFPApplication.getInstance().getEventDispatcher().sendMessage(uimessage);

                    setResult(Activity.RESULT_OK);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {}
        });
    }

}
